﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Drawing;

namespace TerminationCall.Core {

    public class LevelLoader {

        private BinaryReader _binaryReader;
        private Level _level;

        public Level Load(string fileName) {

            _binaryReader = new BinaryReader(File.OpenRead(fileName));

            _level = new Level();
            _level.Background = new Bitmap(Image.FromFile("Background.png"));

            int layerCount = _binaryReader.ReadInt32();

            for (int i = 0; i < layerCount; i++) {

                int horizontalFields = _binaryReader.ReadInt32();
                int verticalFields = _binaryReader.ReadInt32();

                Layer layer = new Layer(horizontalFields);

                _level.Layers.Add(layer);

                for (int x = 0; x < horizontalFields; x++) {
                    for (int y = 0; y < verticalFields; y++) {

                        Field field = layer.Fields[x, y];

                        int tileCount = _binaryReader.ReadInt32();

                        for (int j = 0; j < tileCount; j++) {

                            string tileSetName = _binaryReader.ReadString();
                            TileFields tileFields = (TileFields)Enum.Parse(typeof(TileFields), _binaryReader.ReadString());
                            int numberX = _binaryReader.ReadInt32();
                            int numberY = _binaryReader.ReadInt32();

                            foreach (TileSet tileSet in _level.TileSets) {

                                if (tileSet.Name == tileSetName) {

                                    if (tileFields == TileFields.MiddleTile) {
                                        field.TileField.SetTile(tileSet.Tiles[numberX, numberY]);
                                    } else {
                                        field.TileField.SetTile(tileFields, tileSet.Tiles[numberX, numberY]);
                                    }
                                    break;
                                }

                            }

                        }

                    }

                }

            }

            _binaryReader.Close();

            return _level;
        }
    }
}
